package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.task.ArticleHtmlTasks;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-29
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Autowired
    private ArticleHtmlTasks articleHtmlTasks;

    @Override
    public ResponseResult<Long> saveApArticle(ArticleDto dto) {
//        判断是否有ID
        if (dto.getId()==null) { //新增
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            apArticle.setCreatedTime(new Date());
//            新增文章信息
            this.save(apArticle);
//            新增文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);

//            生成静态页面的方法
            articleHtmlTasks.createArticleHtml(apArticle,dto.getContent());

            return ResponseResult.okResult(apArticle.getId());
        }else{
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            apArticle.setCreatedTime(new Date());
//            修改文章信息
            this.updateById(apArticle);
//           修改文章内容
//            update ap_article_content set content=?? where article_id=??
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent,dto.getContent());
            updateWrapper.eq(ApArticleContent::getArticleId,dto.getId());
            apArticleContentService.update(updateWrapper);

//            生成静态页面的方法
            articleHtmlTasks.createArticleHtml(apArticle,dto.getContent());


            return ResponseResult.okResult(apArticle.getId());
        }

    }

    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {  //0 代表初次加载或加载更新 1代表加载更多

        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
//        查询条件：频道id 如果是0 就是查询所有频道
        if (dto.getChannelId()!=0) {
            queryWrapper.eq(ApArticle::getChannelId,dto.getChannelId());
        }

        if(type==0){
            //        0 代表初次加载或加载更新  发布时间>maxTime
            queryWrapper.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }else{
            //      1代表加载更多  发布时间<minTime
            queryWrapper.lt(ApArticle::getPublishTime,dto.getMinTime());
        }
        //         隐藏了两个条件： 是否下架 是否删除
        queryWrapper.eq(ApArticle::getIsDelete,false);
        queryWrapper.eq(ApArticle::getIsDown,false);
        //        发布时间排序
        queryWrapper.orderByDesc(ApArticle::getPublishTime)  ;

//        分页
        Page<ApArticle> page = new Page<>(1,dto.getSize());

        Page<ApArticle> page1 = this.page(page, queryWrapper);



        return ResponseResult.okResult(page1.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //        查询两个表
//        根据文章id查询ap_article表
        ApArticle apArticle = this.getById(dto.getArticleId());
        if(apArticle==null){
            log.error("查不到数据，文章id是："+dto.getArticleId());
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

//        根据文章id查询 ap_article_content 表
//        select * from ap_article_content where article_id=?
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent apArticleContent = apArticleContentService.getOne(queryWrapper);


        Map resultMap = new HashMap();
        resultMap.put("config",apArticle);
        resultMap.put("content",apArticleContent);

        return ResponseResult.okResult(resultMap);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void compute() {
        //        获取今天时间和 5天前的时间
        //        使用了joda-time中的工具类 ，因为最近测试数据少，这里可以查询200天之前的数据
        Date beforeDate = DateTime.now().minusDays(200).toDate();
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getIsDelete,false);
        queryWrapper.eq(ApArticle::getIsDown,false);
        queryWrapper.ge(ApArticle::getPublishTime,beforeDate);
        List<ApArticle> list = this.list(queryWrapper);


        //        先删除再放数据
        Set<String> keys = redisTemplate.keys("hot_article_first_page_*");

        redisTemplate.delete(keys);



        List<ApArticle> articleList = this.list(queryWrapper);
        for (ApArticle article : articleList) {
            // 计算文章的分值
            int score = computeScore(article);

            ApArticle cache = new ApArticle();

            cache.setId(article.getId());
            cache.setTitle(article.getTitle());
            cache.setImages(article.getImages());
            cache.setAuthorId(article.getAuthorId());
            cache.setAuthorName(article.getAuthorName());
            cache.setLayout(article.getLayout());
            cache.setStaticUrl(article.getStaticUrl());

            String jsonString = JSON.toJSONString(cache); //放的内容是固定不变的，比如点赞数、评论数经常变的属性就不要放了，如果理解不了就直接把article转成json字符串
            //            0代表是首页上推荐的文章
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(jsonString,score);
            //            再放到各自的频道上推荐的文章
            redisTemplate.boundZSetOps("hot_article_first_page_"+article.getChannelId()).add(jsonString,score);

        }

    }

    @Override
    public void updateHotArticle(ArticleStreamMessage message) {

        //       1、重新计算文章的热度值（今天产生的数据*3）
        Long articleId = message.getArticleId();
        ApArticle article = this.getById(articleId);
        int score = computeTodayScore(message);

        ApArticle cache = new ApArticle();

        cache.setId(article.getId());
        cache.setTitle(article.getTitle());
        cache.setImages(article.getImages());
        cache.setAuthorId(article.getAuthorId());
        cache.setAuthorName(article.getAuthorName());
        cache.setLayout(article.getLayout());
        cache.setStaticUrl(article.getStaticUrl());

        //      2、更新redis中的数据
        //        String key = "hot_article_first_page_" + dto.getChannelId();
        Double scoreBefore = redisTemplate.boundZSetOps("hot_article_first_page_0").score(JSON.toJSONString(cache));
        if(scoreBefore!=null){
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),scoreBefore+score);
            redisTemplate.boundZSetOps("hot_article_first_page_"+article.getChannelId()).add(JSON.toJSONString(cache),scoreBefore+score);
        }else{
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),score);
            redisTemplate.boundZSetOps("hot_article_first_page_"+article.getChannelId()).add(JSON.toJSONString(cache),score);
        }

        //     3、更新mysql中ApArticle中的阅读数、点赞数、评论数、收藏数

        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId,message.getArticleId());
        updateWrapper.setSql("views=views+"+message.getView());
        updateWrapper.setSql("likes=likes+"+message.getLike());
        updateWrapper.setSql("comment=comment+"+message.getComment());
        updateWrapper.setSql("collection=collection+"+message.getCollect());
        this.update(updateWrapper);

    }

    /**
     * 计算当日的增量分数  当日的操作整体权重*3
     *
     * @param message
     * @return
     */
    private int computeTodayScore(ArticleStreamMessage message) {
        int score = 0;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return score;
    }

    private int computeScore(ApArticle article) {
        int score = 0;
        // 阅读 +1  点赞 +3  评论 +5  收藏 +8
        if (article.getViews() != null) {
            score += article.getViews() * 1;
        }
        if (article.getLikes() != null) {
            score += article.getLikes() * 3;
        }
        if (article.getComment() != null) {
            score += article.getComment() * 5;
        }
        if (article.getCollection() != null) {
            score += article.getCollection() * 8;
        }
        return score;
    }
}
